package model

import (
	myConfig "common/config"
	myconn "common/conn"
	"common/helper"
	myredis "common/redis"
	myUserHelp "common/userHelp"
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/meilisearch/meilisearch-go"
	"github.com/valyala/fasthttp"
	"math"
	"strconv"
	"strings"
	"time"
)

func GameFullTextMeili(gameType, page, pageSize int, platformId, tagId, word string) (GameData, error) {

	var data GameData

	offset_t := pageSize * (page - 1)

	key := fmt.Sprintf("%d-games", meta.RedisDBIndex)
	index := meta.Meili.Index(key)

	cond := &meilisearch.SearchRequest{
		Limit:  int64(pageSize),
		Offset: int64(offset_t),
	}

	filter := "online = 1"
	if gameType > 0 {
		filter += fmt.Sprintf(" AND game_type = %d", gameType)
	}
	if platformId != "0" {
		filter += fmt.Sprintf(" AND platform_id = %s", platformId)
	}
	if tagId != "0" {
		filter += fmt.Sprintf(" AND tag_ids = %s", tagId)
	}

	cond.Filter = filter
	searchRes, err := index.Search(word, cond)
	if err != nil {
		return data, err
	}
	ll := len(searchRes.Hits)
	if ll == 0 {
		data.S = 0
		data.T = 0
		return data, err
	}
	data.D = make([]TblGameLists, ll)
	data.T = searchRes.EstimatedTotalHits
	data.S = uint(pageSize)

	for i, v := range searchRes.Hits {
		val := v.(map[string]interface{})

		data.D[i].ID = val["id"].(string)
		data.D[i].PlatformID = val["platform_id"].(string)
		data.D[i].Name = ""
		data.D[i].EnName = val["en_name"].(string)
		data.D[i].BrAlias = val["br_alias"].(string)
		data.D[i].ClientType = val["client_type"].(string)
		data.D[i].GameType = int(val["game_type"].(float64))
		data.D[i].GameID = val["game_id"].(string)
		data.D[i].Img = val["img"].(string)
		data.D[i].Online = int(val["online"].(float64))
		data.D[i].IsHot = int(val["is_hot"].(float64))
		data.D[i].IsFav = int(val["is_fav"].(float64))
		data.D[i].IsNew = int(val["is_new"].(float64))
		data.D[i].Maintained = int(val["maintained"].(float64))

	}

	return data, nil

}

func GameListMeili(fctx *fasthttp.RequestCtx, gameType, hot, page, pageSize int, platformId, gameName, field string) (GameData, error) {

	uid := myUserHelp.GetUidFromToken(fctx)
	myUserHelp.AddUserDailyAction(uid, myUserHelp.Action_Login)

	var (
		data GameData
		gids []interface{}
	)

	offset_t := pageSize * (page - 1)

	key := fmt.Sprintf("%d-games", meta.RedisDBIndex)
	index := meta.Meili.Index(key)

	var sort string
	if field == "is_hot" {
		sort = "hot_sort:desc"
	} else if field == "is_new" {
		sort = "new_sort:desc"
	} else if field == "is_fav" {
		sort = "fav_sort:desc"
	}
	//wildcardQuery := fmt.Sprintf("*%s*", gameName)
	cond := &meilisearch.SearchRequest{
		Limit:  int64(pageSize),
		Offset: int64(offset_t),
		Sort:   []string{sort},
	}

	filter := "online = 1"
	if gameType > 0 {
		if field == "is_new" {
			filter += fmt.Sprintf(" AND game_type = %d ", gameType)
		} else {
			filter += fmt.Sprintf(" AND game_type = %d AND %s = 1", gameType, field)
		}

	} else {
		if field != "is_new" {
			filter += fmt.Sprintf(" AND %s = 1", field)
		}
	}

	//if platformId != "0" {
	//	filter += fmt.Sprintf(" AND platform_id = %s", platformId)
	//}
	if platformId != "0" {
		// 如果 platformId 包含逗号，则进行多个平台ID的查询
		if strings.Contains(platformId, ",") {
			// 如果 platformId 包含逗号，则构建多个平台ID的过滤条件
			platformIds := strings.Split(platformId, ",")
			platformFilters := make([]string, len(platformIds))
			for i, id := range platformIds {
				platformFilters[i] = fmt.Sprintf("platform_id = %s", id)
			}
			filter += " AND (" + strings.Join(platformFilters, " OR ") + ")"
		} else {
			// 否则，构建单个平台ID的过滤条件
			filter += fmt.Sprintf(" AND platform_id = %s", platformId)
		}

	}

	if hot > 0 {
		filter += fmt.Sprintf(" AND is_hot = %d", hot)
	}

	cond.Filter = filter
	searchRes, err := index.Search("", cond)
	if err != nil {
		return data, err
	}

	ll := len(searchRes.Hits)
	if ll == 0 {
		return data, err
	}

	gids = make([]interface{}, ll)
	data.D = make([]TblGameLists, ll)
	data.T = searchRes.EstimatedTotalHits
	data.S = uint(pageSize)

	for i, v := range searchRes.Hits {
		val := v.(map[string]interface{})

		data.D[i].ID = val["id"].(string)
		data.D[i].PlatformID = val["platform_id"].(string)
		data.D[i].Name = ""
		data.D[i].EnName = val["en_name"].(string)
		data.D[i].BrAlias = val["br_alias"].(string)
		data.D[i].ClientType = val["client_type"].(string)
		data.D[i].GameType = int(val["game_type"].(float64))
		data.D[i].GameID = val["game_id"].(string)
		data.D[i].Img = val["img"].(string)
		data.D[i].Online = int(val["online"].(float64))
		data.D[i].IsHot = int(val["is_hot"].(float64))
		data.D[i].IsFav = 2
		data.D[i].Sorting = int(val["sorting"].(float64))
		data.D[i].IsNew = int(val["is_new"].(float64))
		data.D[i].Maintained = int(val["maintained"].(float64))

		gids[i] = val["id"].(string)
	}

	return data, nil
}

func GameListQuery(fctx *fasthttp.RequestCtx, gameType, hot, page, pageSize int, platformId, gameName, field string) (GameData, error) {

	uid := myUserHelp.GetUidFromToken(fctx)
	myUserHelp.AddUserDailyAction(uid, myUserHelp.Action_Login)

	var (
		data GameData
		//gids []interface{}
	)
	ex := g.Ex{}
	ex["online"] = 1
	if gameType > 0 {
		ex["a.game_type"] = gameType
	}
	if gameName != "" {
		Condition := fmt.Sprintf("%%%s%%", gameName)
		ex["br_alias"] = g.Op{"LIKE": Condition}
	}

	if hot > 0 {
		ex["is_hot"] = hot
	}
	if platformId != "0" {
		// 如果 platformId 包含逗号，则进行多个平台ID的查询
		if strings.Contains(platformId, ",") {
			// 如果 platformId 包含逗号，则构建多个平台ID的过滤条件
			platformIds := strings.Split(platformId, ",")
			//platformFilters := make([]string, len(platformIds))
			//for i, id := range platformIds {
			//	platformFilters[i] = fmt.Sprintf("platform_id = %s", id)
			//}
			ex["platform_id"] = g.Op{"IN": platformIds}
		} else {
			ex["platform_id"] = platformId
		}

	}

	var sort string
	if field == "is_hot" {
		sort = "hot_sort"
	} else if field == "is_new" {
		sort = "new_sort"
	} else if field == "is_fav" {
		sort = "fav_sort"
	}
	t := dialect.From(g.T("tbl_game_lists").As("a"))
	joinCondition := g.On(g.I("a.platform_id").Eq(g.I("b.id")))

	t = t.Join(g.T("tbl_platforms").As("b"), joinCondition).Where(g.I("b.state").Eq(1))

	if page == 1 {
		countQuery, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()
		countQuery = strings.Replace(countQuery, "BINARY", "", 1)
		err := meta.MerchantDB.Get(&data.T, countQuery)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), countQuery), helper.DBErr)
		}
		if data.T == 0 {
			return data, nil
		}
	}

	data.S = uint(pageSize)
	offset := uint((page - 1) * pageSize)
	query, _, _ := t.Select("a.*").Where(ex).Order(g.C(sort).Desc()).Offset(offset).Limit(data.S).ToSQL()
	query = strings.Replace(query, "BINARY", "", 1)
	str1 := " and b.pid/10*10 in(SELECT id FROM tbl_platforms where pid=0 and state=1) ORDER BY"
	query = strings.Replace(query, "ORDER BY", str1, 1)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	return data, nil
}
func GameList(fctx *fasthttp.RequestCtx, page, pageSize int, filter string) (GameData, error) {

	var (
		data GameData
		gids []interface{}
	)

	offset_t := pageSize * (page - 1)

	key := fmt.Sprintf("%d-games", meta.RedisDBIndex)
	index := meta.Meili.Index(key)

	cond := &meilisearch.SearchRequest{
		Limit:  int64(pageSize),
		Offset: int64(offset_t),
		// 设置排序规则
		Sort: []string{"sorting:desc"}, // 按发布日期降序排列
	}

	cond.Filter = filter
	searchRes, err := index.Search("", cond)
	if err != nil {
		return data, err
	}
	ll := len(searchRes.Hits)
	if ll == 0 {
		data.S = 0
		data.T = 0
		return data, err
	}

	gids = make([]interface{}, ll)
	data.D = make([]TblGameLists, ll)
	data.T = searchRes.EstimatedTotalHits
	data.S = uint(pageSize)

	for i, v := range searchRes.Hits {
		val := v.(map[string]interface{})

		data.D[i].ID = val["id"].(string)
		data.D[i].PlatformID = val["platform_id"].(string)
		data.D[i].Name = ""
		data.D[i].EnName = val["en_name"].(string)
		data.D[i].BrAlias = val["br_alias"].(string)
		data.D[i].ClientType = val["client_type"].(string)
		data.D[i].GameType = int(val["game_type"].(float64))
		data.D[i].GameID = val["game_id"].(string)
		data.D[i].Img = val["img"].(string)
		data.D[i].Online = int(val["online"].(float64))
		data.D[i].IsHot = int(val["is_hot"].(float64))
		data.D[i].IsFav = 2
		data.D[i].Sorting = int(val["sorting"].(float64))
		data.D[i].IsNew = int(val["is_new"].(float64))
		data.D[i].Maintained = int(val["maintained"].(float64))

		gids[i] = val["id"].(string)
	}

	return data, nil
}

type GameRsp struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data string `json:"data"`
}

func Launch(args map[string]string, platformId string) (GameRsp, error) {
	rsp := GameRsp{}
	var CfgEvoEnterLimit float64
	if platformId == helper.PPVideo || platformId == helper.EvoVideo {
		Uid := args["uid"]
		CfgEvoEnterLimit = myConfig.GetGameCfgFloat64(myConfig.CfgEvoEnterLimit)
		Balance := myUserHelp.GetBalanceFloat64ByUid(Uid)

		if Balance < CfgEvoEnterLimit {
			rsp.Msg = helper.EvoEnterLimitErr
			rsp.Data = strconv.FormatFloat(CfgEvoEnterLimit, 'f', -1, 64)
			return rsp, errors.New(helper.EvoEnterLimitErr)
		}
	}
	headers := map[string]string{
		"Content-Type": "application/json;charset=utf-8",
	}

	requestURI := SwitchPid(platformId)
	sign, err := LaunchSignValidate(args)
	helper.InfoLog("sign:%s", sign)
	if err != nil {
		helper.SqlSelectErrLog("sign:%s", sign)
		return rsp, err
	}
	args["sign"] = sign
	requestParams, _ := helper.JsonMarshal(args)

	helper.InfoLog("requestURI:%s---%s", requestURI, string(requestParams))
	statusCode, body, err := myconn.HttpPostHeader(requestParams, requestURI, headers)

	if err != nil {
		helper.SqlSelectErrLog("requestURI:%s\nargs:%s\nbody:%s\nerr:%s", requestURI, args, string(body), err.Error())
		return rsp, errors.New(helper.PlatformLoginErr)
	}

	if statusCode != fasthttp.StatusOK {
		helper.SqlSelectErrLog("statusCode:%d", statusCode)
		helper.InfoLog("requestURI:%s args:%s body:%s", requestURI, args, string(body))
		return rsp, errors.New(helper.PlatformLoginErr)
	}

	err = helper.JsonUnmarshal(body, &rsp)
	if err != nil {
		helper.SqlSelectErrLog("Launch:format:%s", string(body), err)
		return rsp, errors.New(helper.FormatErr)
	}

	//if rsp.Code == 0 {
	//	return rsp.Data, nil
	//} else {
	//	return "", errors.New(rsp.Msg)
	//}
	return rsp, nil

}

func Transaction(args GameParam, content string) (string, bool) {
	if !TransactionSignValidate(args, content) {
		return "0", false
	}
	switch args.Cmd {
	case GetBalance:
		return ThirdGameBalance(content)
	case BetAmount:
		return ThirdGameTransferSub(content)
	case WinAmount:
		return ThirdGameTransferAdd(content)
	}

	return "", true
}

func ThirdGameBalance(content string) (string, bool) {
	tThirdBalance := ThirdBalance{}
	err := json.Unmarshal([]byte(content), &tThirdBalance)
	if err != nil {
		helper.GetloggerInstance().Warning(content)
		return "0", false
	}

	CfgPlatMaxWin := myConfig.GetGameCfgFloat64(myConfig.CfgPlatMaxWin)

	PlayerTotalWin, _ := GetRedisInstance().HGet(context.Background(), "PlatformRun", "PlayerTotalWin").Result()
	PlayerTotalBet, _ := GetRedisInstance().HGet(context.Background(), "PlatformRun", "PlayerTotalBet").Result()

	fPlayerTotalWin, _ := strconv.ParseFloat(PlayerTotalWin, 64)
	fPlayerTotalBet, _ := strconv.ParseFloat(PlayerTotalBet, 64)

	if fPlayerTotalBet-fPlayerTotalWin >= CfgPlatMaxWin && CfgPlatMaxWin > 0 {
		helper.GetloggerInstance().Warning(content)
		return "0", false
	}

	strBalance := myUserHelp.GetBalanceStringByUid(tThirdBalance.Uid)
	return strBalance, true
}

/*
接收php 获取余额
*/
type ThirdBalance struct {
	Uid string `json:"uid"`
}

/*
接收php 游戏结果
*/
type ThirdGameResult struct {
	Uid           string  `json:"uid"`
	TransactionId string  `json:"transaction_id"`
	PlatformId    string  `json:"platform_id"` //这个PlatformId是大类 100 200 300
	Bet           float64 `json:"bet"`
	WinAmount     float64 `json:"winAmount"`
	GameId        string  `json:"game_id"`
}

func ThirdGameTransferAdd(content string) (string, bool) {
	GameResult := ThirdGameResult{}
	err := json.Unmarshal([]byte(content), &GameResult)
	if err != nil {
		return "1", false
	}

	Uid := GameResult.Uid
	GameResult.Bet = math.Abs(GameResult.Bet)

	var routeName string = ""
	if GameResult.PlatformId == "juhe" {
		FakePlatId := myConfig.FindFakePlatByFakeId(GameResult.GameId)
		GameResult.PlatformId = FakePlatId
		routeName = myConfig.FakeGameRouteName(GameResult.PlatformId)
	}

	bigPlatFormId, _ := strconv.ParseInt(GameResult.PlatformId, 10, 64)

	// 测试号
	if myUserHelp.GetMemberTester(Uid) == 2 {
		myUserHelp.AddUserBalanceByFloat64(Uid, GameResult.WinAmount)
		return "0", true
	}

	GameTax := myUserHelp.GetGameTax(Uid, GameResult.PlatformId, GameResult.WinAmount, GameResult.Bet)
	realWin := GameResult.WinAmount - GameTax

	platIdInt, _ := strconv.ParseInt(GameResult.PlatformId, 10, 64)
	if platIdInt >= 3000 {
		platIdInt = platIdInt / 10 * 10
	}

	platIdStr := fmt.Sprintf("%d", platIdInt)

	myUserHelp.AddBalanceTransactionRecord(Uid, realWin, helper.TransactionPayout, platIdStr, GameResult.TransactionId, GameTax, GameResult.GameId, routeName, 0)

	myUserHelp.AddUserBalanceByFloat64(Uid, realWin)

	//游戏过程爆奖 增加需要的打码量
	myUserHelp.AddGameWaged(Uid, GameResult.WinAmount, GameResult.Bet)

	//PlatformId 二级分类比101
	PlatformId := myConfig.FindPlatformByGame(GameResult.GameId, int(bigPlatFormId))
	strPlatformId := fmt.Sprintf("%d", PlatformId/10*10)

	//helper.InfoLog("ThirdGameTransferAdd:strPlatformId---%s", strPlatformId)
	if strPlatformId == "0" {
		strPlatformId = helper.PG
	}

	//helper.InfoLog("ThirdGameTransferAdd:strPlatformId---%s", strPlatformId)
	myredis.AddProxyBusiDataByFloat64(Uid, strPlatformId+":gameTax", GameTax)
	myredis.AddProxyBusiDataByFloat64(Uid, strPlatformId+":gameWinLost", GameResult.WinAmount)

	//增加自己的统计
	myUserHelp.AddGameTax(Uid, GameTax)
	myUserHelp.AddTotalGameWinLost(Uid, GameResult.WinAmount)

	ValidWaged := myUserHelp.CalcValidWaged(Uid, strPlatformId, GameResult.WinAmount, GameResult.Bet)
	myredis.AddProxyBusiDataByFloat64(Uid, strPlatformId+":validWaged", ValidWaged)
	myUserHelp.AddTotalWaged(Uid, ValidWaged)
	myUserHelp.AddEnableLuckyPoint(Uid, ValidWaged) //增加幸运点数
	myUserHelp.AddUserWageRequire(Uid, ValidWaged, 0)

	GetRedisInstance().HIncrByFloat(context.Background(), "PlatformRun", "PlayerTotalWin", GameResult.WinAmount)
	GetRedisInstance().Expire(context.Background(), "PlatformRun", time.Duration(24*365)*time.Hour)
	if myConfig.GetGameCfgFloat64(myConfig.CfgValidInviteWagedReq) > 0.00 && ValidWaged > 0.00 {
		FirstDepositAmount := myUserHelp.GetFirstDepositAmount(Uid)
		TotalDeposit := myUserHelp.GetTotalDeposit(Uid)

		ValidInviteCodition := myConfig.GetGameCfgInt(myConfig.CfgValidInviteCondition)

		var bValidInvite bool
		bValidInvite = false

		//首冲
		if ValidInviteCodition == 0 && FirstDepositAmount >= myConfig.GetGameCfgFloat64(myConfig.CfgValidInviteMinDeposit) {
			bValidInvite = true
		}

		//累计
		if ValidInviteCodition > 0 && (TotalDeposit) >= myConfig.GetGameCfgFloat64(myConfig.CfgValidInviteMinDeposit) {
			bValidInvite = true
		}

		if bValidInvite &&
			myUserHelp.GetTotalWaged(Uid) >= myConfig.GetGameCfgFloat64(myConfig.CfgValidInviteWagedReq) &&
			myUserHelp.GetTotalWaged(Uid)-ValidWaged < myConfig.GetGameCfgFloat64(myConfig.CfgValidInviteWagedReq) {
			myUserHelp.ProcessValidInvite(Uid)
		}
	}
	ParentId := myUserHelp.GetProxyParentId(Uid)
	if ParentId != "0" {
		//首充梯度奖励
		if myUserHelp.GetTotalWaged(Uid) >= myConfig.GetGameCfgFloat64(myConfig.CfgFirstDepositBonusWaged) &&
			myUserHelp.GetTotalWaged(Uid)-ValidWaged <= myConfig.GetGameCfgFloat64(myConfig.CfgFirstDepositBonusWaged) {
			CalDepositBonus(Uid)
		}

		//分成奖励
		if myUserHelp.G_UserButton.GetRechargeButton(ParentId) == 1 {

		} else {
			if myUserHelp.GetTotalWaged(Uid) >= myConfig.GetGameCfgFloat64(myConfig.CfgRechargeShareWagedReq) &&
				myUserHelp.GetTotalWaged(Uid)-ValidWaged <= myConfig.GetGameCfgFloat64(myConfig.CfgRechargeShareWagedReq) {
				CalRechargeShare(Uid, 1)
			}
		}
		grandId := myUserHelp.GetProxyGrandId(Uid)
		if grandId != "0" {
			if myUserHelp.G_UserButton.GetRechargeButton(grandId) == 1 {

			} else {
				if myUserHelp.GetTotalWaged(Uid) >= myConfig.GetGameCfgFloat64(myConfig.CfgRechargeShareWagedReq) &&
					myUserHelp.GetTotalWaged(Uid)-ValidWaged <= myConfig.GetGameCfgFloat64(myConfig.CfgRechargeShareWagedReq) {
					CalRechargeShare(Uid, 2)
				}
			}
			greatGrandId := myUserHelp.GetProxyGreatGrandId(Uid)
			if greatGrandId != "0" {
				if myUserHelp.G_UserButton.GetRechargeButton(greatGrandId) == 1 {

				} else {
					if myUserHelp.GetTotalWaged(Uid) >= myConfig.GetGameCfgFloat64(myConfig.CfgRechargeShareWagedReq) &&
						myUserHelp.GetTotalWaged(Uid)-ValidWaged <= myConfig.GetGameCfgFloat64(myConfig.CfgRechargeShareWagedReq) {
						CalRechargeShare(Uid, 3)
					}
				}
			}
		}
	}

	return "0", true
}

func CalRechargeShare(uid string, level int) {
	//用户变成有效用户 处理充值分成奖励
	switch level {
	case 1:
		ParentId := myUserHelp.GetProxyParentId(uid)
		if ParentId != "0" {
			lvShare := myUserHelp.GetRechargeShare(uid, 1)
			if lvShare > 0.0 {
				myUserHelp.AddEnableRechargeShare(ParentId, 1, lvShare)
				myUserHelp.AutoRechargeShare(uid, ParentId, lvShare, 1)
				myUserHelp.ClearDisableRechargeShare(uid, 1)
			}
		}
	case 2:
		GrandId := myUserHelp.GetProxyGrandId(uid)
		if GrandId != "0" {
			lvShare := myUserHelp.GetRechargeShare(uid, 2)
			if lvShare > 0.0 {
				myUserHelp.AddEnableRechargeShare(GrandId, 2, lvShare)
				myUserHelp.AutoRechargeShare(uid, GrandId, lvShare, 2)
				myUserHelp.ClearDisableRechargeShare(uid, 2)
			}
		}
	case 3:
		GrandGreatId := myUserHelp.GetProxyGreatGrandId(uid)
		if GrandGreatId != "0" {
			lvShare := myUserHelp.GetRechargeShare(uid, 3)
			if lvShare > 0.0 {
				myUserHelp.AddEnableRechargeShare(GrandGreatId, 3, lvShare)
				myUserHelp.AutoRechargeShare(uid, GrandGreatId, lvShare, 3)
				myUserHelp.ClearDisableRechargeShare(uid, 3)
			}
		}
	}
}

/*
接收php 三方下注操作
*/
type ThirdGameBet struct {
	Uid           string  `json:"uid"`
	TransactionId string  `json:"transaction_id"`
	PlatformId    string  `json:"platform_id"`
	GameId        string  `json:"game_id"`
	Bet           float64 `json:"bet"`
}

func ThirdGameTransferSub(content string) (string, bool) {
	GameBet := ThirdGameBet{}
	err := json.Unmarshal([]byte(content), &GameBet)
	if err != nil {
		return "4", false
	}

	if GameBet.Bet < 0.0 {
		return "1", false
	}

	var routeName string = ""
	if GameBet.PlatformId == "juhe" {
		FakePlatId := myConfig.FindFakePlatByFakeId(GameBet.GameId)
		GameBet.PlatformId = FakePlatId
		routeName = myConfig.FakeGameRouteName(GameBet.PlatformId)
	}

	bigPlatFormId, _ := strconv.ParseInt(GameBet.PlatformId, 10, 64)
	Uid := GameBet.Uid
	GameBet.Bet = math.Abs(GameBet.Bet)
	myUserHelp.LoadUserToRedis(Uid)

	if myUserHelp.GetBalanceFloat64ByUid(Uid) < GameBet.Bet {
		//打日志
		helper.GetloggerInstance().Emergencyf("ThirdGameTransferSub:	%s----%s----%0.3f", Uid, myUserHelp.GetBalanceStringByUid(Uid), GameBet.Bet)
		return "3", false
	}

	//helper.GetloggerInstance().Infof("ThirdGameTransferSub:%s", content)
	if myUserHelp.GetMemberTester(Uid) != 2 {
		platIdInt, _ := strconv.ParseInt(GameBet.PlatformId, 10, 64)
		if platIdInt >= 3000 {
			platIdInt = platIdInt / 10 * 10
		}

		platIdStr := fmt.Sprintf("%d", platIdInt)
		myUserHelp.AddBalanceTransactionRecord(Uid, -GameBet.Bet, helper.TransactionBet, platIdStr, GameBet.TransactionId, 0.00, GameBet.GameId, routeName, 0)
	}

	//减余额
	myUserHelp.AddUserBalanceByFloat64(Uid, -GameBet.Bet)

	// 测试号
	if myUserHelp.GetMemberTester(Uid) == 2 {
		return "0", true
	}

	//PlatformId 二级分类比101
	PlatformId := myConfig.FindPlatformByGame(GameBet.GameId, int(bigPlatFormId))
	strPlatformId := fmt.Sprintf("%d", PlatformId/10*10)

	if strPlatformId == "0" {
		strPlatformId = helper.PG
	}

	ValidRunning := myUserHelp.CalcValidRunning(Uid, 0.0, GameBet.Bet)

	myredis.AddProxyBusiDataByFloat64(Uid, strPlatformId+":running", ValidRunning)
	myredis.AddProxyBusiDataByFloat64(Uid, strPlatformId+":gameRound", 1)

	myUserHelp.AddGameRunning(Uid, GameBet.Bet)
	myUserHelp.AddGameRound(Uid, 1)

	GetRedisInstance().HIncrByFloat(context.Background(), "PlatformRun", "PlayerTotalBet", GameBet.Bet)
	GetRedisInstance().Expire(context.Background(), "PlatformRun", time.Duration(24*365)*time.Hour)
	return "0", true
}

func LaunchSignValidate(args map[string]string) (string, error) {

	//content = fmt.Sprintf(`uid=%s&gtype=%s&gameid=%s&test=%s&key=%s`, args["uid"], args["gtype"], args["gameid"], args["test"], "game_create_key_qwe123")
	content := fmt.Sprintf(`%s%s%s%s%s`, args["uid"], args["gtype"], args["gameid"], args["test"], "game_create_key_qwe123")
	sign := helper.MD5Hash(content)
	return sign, nil
}

func TransactionSignValidate(args GameParam, content string) bool {
	//对结果sign验证
	data := fmt.Sprintf(`%s%s`, content, "opulentpeng-009")
	sign := helper.MD5Hash(data)
	if args.Sign != sign {
		helper.InfoLog("sign error:  old sign=%s, new state=%s", args.Sign, sign)
		return false
	}
	return true
}

func SwitchPid(pid string) string {
	url := myConfig.GetGameCfgString(myConfig.CfgForwardingDomain)

	data := url + "/fakejh/Index/createuser"

	helper.InfoLog("SwitchPid:%s", data)
	return data
}

type PlatformGameNumber struct {
	PlatformName string `json:"platform_id"`
	Number       int64  `json:"number"`
}

func GetBigPlatFormId(platformId string) string {
	var bigPlatFormId int64 = 0
	if helper.PPSlot == platformId || helper.PPlive == platformId || helper.PPVideo == platformId {
		bigPlatFormId = 200
	}

	bigPlatFormId, _ = strconv.ParseInt(platformId, 10, 64)
	bigPlatFormId = bigPlatFormId / 10 * 10
	return strconv.FormatInt(bigPlatFormId, 10)
}

func GameNumber() ([]PlatformGameNumber, error) {

	var data PlatformGameNumber
	var resp []PlatformGameNumber

	for name, id := range Platforms {
		filter := "online = 1"
		if id != "" {
			// 如果 platformId 包含逗号，则进行多个平台ID的查询
			if strings.Contains(id, ",") {
				// 如果 platformId 包含逗号，则构建多个平台ID的过滤条件
				platformIds := strings.Split(id, ",")
				platformFilters := make([]string, len(platformIds))
				for j, id := range platformIds {
					platformFilters[j] = fmt.Sprintf("platform_id = %s", id)
				}
				filter += " AND (" + strings.Join(platformFilters, " OR ") + ")"

			} else if id == "0" {
				// 否则，构建单个平台ID的过滤条件
				filter = "online = 1"
			} else {
				// 否则，构建单个平台ID的过滤条件
				filter += fmt.Sprintf(" AND platform_id = %s", id)
			}

			key := fmt.Sprintf("%d-games", meta.RedisDBIndex)
			index := meta.Meili.Index(key)

			cond := &meilisearch.SearchRequest{}
			cond.Filter = filter
			searchRes, err := index.Search("", cond)
			if err != nil {
				return resp, err
			}
			data.PlatformName = name
			data.Number = searchRes.EstimatedTotalHits
			resp = append(resp, data)

		}
	}

	return resp, nil
}

func CalDepositBonus(uid string) {
	ParentId := myUserHelp.GetProxyParentId(uid)
	if ParentId != "0" {
		bonus := myUserHelp.GetDepositBonus(uid)
		if bonus > 0.0 {
			myUserHelp.AddEnableDepositBonus(ParentId, bonus)
			myUserHelp.AutoDepositBonus(uid, ParentId, bonus)
			myUserHelp.ClearDisableDepositBonus(uid)
		}
	}

}

func PlatformList() ([]PlatJson, error) {
	var data []PlatJson
	//	ex := g.Ex{"pid": 0, "state": 1}
	//	query, _, _ := dialect.From("tbl_platforms").Select(colsPlatform...).Where(ex).Where(g.)Order(g.C("seq").Asc()).ToSQL()

	query := fmt.Sprintf("select id,name,game_type,state,maintained,seq from tbl_platforms " +
		"	where state=1 and pid=0 and  id < 3000 " +
		"	order by seq asc")
	err := meta.MerchantDB.Select(&data, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}
	return data, nil
}
